package cn.stylefeng.guns.modular.shuheng.controller;

import cn.stylefeng.guns.config.properties.GunsProperties;
import cn.stylefeng.guns.core.common.annotion.BussinessLog;
import cn.stylefeng.guns.core.common.constant.Constants;
import cn.stylefeng.guns.core.common.constant.dictmap.FilesDict;
import cn.stylefeng.guns.core.common.constant.dictmap.RoleDict;
import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import cn.stylefeng.guns.core.common.node.ZTreeNode;
import cn.stylefeng.guns.core.common.page.LayuiPageFactory;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.shiro.ShiroUser;
import cn.stylefeng.guns.core.util.FileUtil;
import cn.stylefeng.guns.core.util.UUIDUtil;
import cn.stylefeng.guns.modular.shuheng.entity.*;
import cn.stylefeng.guns.modular.shuheng.service.*;
import cn.stylefeng.guns.modular.shuheng.warpper.DataWrapper;
import cn.stylefeng.guns.modular.shuheng.warpper.FilesWrapper;
import cn.stylefeng.guns.modular.system.entity.Dept;
import cn.stylefeng.guns.modular.system.service.DeptService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

@RequestMapping("score")
@Controller
public class ScoreController extends BaseController {
    private String PREFIX = "/modular/shuheng/score/";

    @Autowired
    private DataService dataService;

    @Autowired
    private LevelService levelService;

    @Autowired
    private FilesService filesService;

    @Autowired
    private GunsProperties gunsProperties;

    @Autowired
    private DeptService deptService;

    @Autowired
    private RegionService regionService;

    @Autowired
    private ScoreService scoreService;

    @RequestMapping("")
    public String index(@RequestParam(value = "year",required = false) Integer year,
                        @RequestParam(value = "month",required = false) Integer month,
                        @RequestParam(value = "cityName",required = false)String cityName, Model model){
        Calendar calendar = Calendar.getInstance();
        Integer nowYear = calendar.get(Calendar.YEAR);
        List<Integer> list = new ArrayList<>();
        list.add(nowYear);
        list.add(nowYear +1);
        list.add(nowYear +2);
        model.addAttribute("yearList",list);
        if(ToolUtil.isEmpty(year)){
            year = nowYear;
        }
        ShiroUser user = ShiroKit.getUser();
        model.addAttribute("userLevel",user.getUserLevel());
        model.addAttribute("userCity",user.getCity());

        if(ToolUtil.isNotEmpty(cityName)){
            Region region = regionService.getByRegionName(cityName);
            if(region!=null){
                model.addAttribute("regionId",region.getRegionId());
            }
        }else {
            model.addAttribute("regionId","");
        }

        return PREFIX + "score.html";
    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(value = "condition", required = false) String condition,
                       @RequestParam(value = "parentId", required = false) Long parentId,
                       @RequestParam(value = "year",required = false) Integer year,
                       @RequestParam(value = "month",required = false) String[] month,
                       @RequestParam(value = "status",required = false) Integer status,
                       @RequestParam(value = "level", required = false) Integer level,
                       @RequestParam(value = "city",required = false) Long city,
                       @RequestParam(value = "county",required = false) Long county,
                       @RequestParam(value = "score",required = false) BigDecimal score) {
        Calendar calendar = Calendar.getInstance();
        Integer nowYear = calendar.get(Calendar.YEAR);
        if(year==null){
            year = nowYear;
        }
        if(ToolUtil.isEmpty(level)){
            level = 3;
        }
        String[] quarterArr = null;
        if(month!=null && month.length>0){
            quarterArr = month;
        }
        Page<Map<String, Object>> list = this.filesService.listFiles(condition, parentId,year,level,city,county,score,status,quarterArr);
        Page<Map<String, Object>> wrap = new FilesWrapper(list).wrap();
        return LayuiPageFactory.createPageInfo(wrap);
    }

    /**
     * 导出excel
     * @return
     */
    @RequestMapping("/exportExcel")
    @ResponseBody
    public List<Map<String,Object>> exportExcel(@RequestParam(value = "condition", required = false) String condition,
                                                @RequestParam(value = "parentId", required = false) Long parentId,
                                                @RequestParam(value = "year",required = false) Integer year,
                                                @RequestParam(value = "month",required = false) String[] month,
                                                @RequestParam(value = "status",required = false) Integer status,
                                                @RequestParam(value = "level", required = false) Integer level,
                                                @RequestParam(value = "city",required = false) Long city,
                                                @RequestParam(value = "county",required = false) Long county,
                                                @RequestParam(value = "score",required = false) BigDecimal score){
        Calendar calendar = Calendar.getInstance();
        Integer nowYear = calendar.get(Calendar.YEAR);
        if(year==null){
            year = nowYear;
        }
        if(ToolUtil.isEmpty(level)){
            level = 3;
        }
        String[] quarterArr = null;
        if(month!=null && month.length>0){
            quarterArr = month;
        }
        List<Map<String, Object>> list = this.filesService.listExcelFiles(condition, parentId,year,level,city,county,score,status,quarterArr);
        list = new FilesWrapper(list).wrap();
        return list;
    }



    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> tree(@RequestParam(value = "year",required = false) Integer year,
                                @RequestParam(value = "level",required = false) Integer level) {
        List<ZTreeNode> tree = this.levelService.tree(year,level);
        tree.add(ZTreeNode.createParent());
        return tree;
    }


    /**
     * 跳转导入页面
     * @return
     */
    @RequestMapping("/toImport")
    public String toImport(){
        return PREFIX + "import.html";
    }

    /**
     * 导入已完成任务
     * 省级导入市级的（带着区县的）
     * 市级导入区县的
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/import")
    @ResponseBody
    @Transactional
    public Map import_(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        ShiroUser user = ShiroKit.getUser();
        String path = (String) request.getParameter("path");
        if(ToolUtil.isEmpty(path)){
            path = Constants.ZIP_PATH;
        }else{
            path = Constants.UPLOAD_PATH + path + File.separator;
        }
        Map data = new HashMap();
        data.put("code",0);
        data.put("msg","导入完成");
        // 视频路径
        String filePath = "";
        // 视频名称
//        String orgFileName = null;
        // 视频后缀
        String fileExt = null;
        // 文件格式错误信息
        String fileExtError = null;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件
            MultipartFile mf = entity.getValue();
            // 获取文件大小
            long picSize = mf.getSize();
            // 获取原文件名
            String fileName =  mf.getOriginalFilename();
            // 获取图片后缀
            fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (!Constants.ZIP.equals(fileExt)) {
                fileExtError = "请上传zip格式文件";
                data.put("code","1");
                data.put("msg",fileExtError);
                return data;
            } else if (picSize > Constants.ONE_HUNDRED_MB * 10) {
                fileExtError = "文件最大1000M";
                data.put("code","2");
                data.put("msg",fileExtError);
                return data;
            } else {
                // 对原文件名进行重命名
                fileName = UUIDUtil.uuid() + "." + fileExt;
                // 返回文件路径
                String rootPath = FileUtil.getRootPath(request,gunsProperties.getJarName());
                filePath = path + fileName;
                File dic = new File(rootPath + path);
                if(!dic.exists()){
                    dic.mkdirs();
                }
                //上传至服务器
                String realPath = rootPath + filePath;
                mf.transferTo(new File(realPath));

                //上传成功后读取zip
                ZipFile zipFile = new ZipFile(realPath);
                InputStream in = new BufferedInputStream(new FileInputStream(realPath));
                ZipInputStream zin = new ZipInputStream(in);
                ZipEntry ze;
                StringBuffer json = new StringBuffer();
                Map<String,InputStream> streamMap = new HashMap<>();
                while((ze = zin.getNextEntry()) != null){
                    if(ze.toString().endsWith("json")){
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(zipFile.getInputStream(ze)));
                        String line;
                        while((line = br.readLine()) != null){
                            json.append(line);
                        }
                        br.close();
                    }else{
                        //复制到  File dic = new File(rootPath + Constants.UPLOAD_PATH + data.getDataYear());
                        streamMap.put(ze.getName(),zipFile.getInputStream(ze));
                    }
                }
                zin.close();
                in.close();

                JSONObject jsonObject = JSON.parseObject(json.toString());
                JSONArray filesArr = jsonObject.getJSONArray("listFiles");
                List<Files> filesList = new ArrayList<>();
//                Integer regionLevel = 0;
//                Long city = 0L;
//                Long county = 0L;
                Integer year=0;
                for(int i=0;i<filesArr.size();i++){
                    Files files = JSON.toJavaObject(filesArr.getJSONObject(i),Files.class);
                    filesList.add(files);
                    if(i==0){
//                        city = files.getCity();
//                        county = files.getCounty();
                        year = files.getYear();
                    }
                }
                //如果有之前导入的任务，先删除,省级用户删除市及市下区县的。市级用户删除区县的
//                if(user.getUserLevel()==1){
//                    //省级的。不传county
//                    county = null;
//                }
//                filesService.deleteByYear(year,city,county);
                //将文件导入rootPath + Constants.UPLOAD_PATH + data.getDataYear()
                File yearDic = new File(rootPath+ Constants.UPLOAD_PATH + year);//先创建年份目录
                if(!yearDic.exists()){
                    yearDic.mkdirs();
                }
                for(Map.Entry<String, InputStream> entry : streamMap.entrySet()){
                    String name = entry.getKey();
                    InputStream inputStream = (InputStream) entry.getValue();
                    FileUtil.copyFile(inputStream,rootPath+ Constants.UPLOAD_PATH + year+File.separator + name);
                }

                List<Files> saveFiles = new ArrayList<>();//如果出现任务变动
                for(int i=0;i<filesList.size();i++){
                    File file = new File(rootPath + filesList.get(i).getFilePath());
                    if(file.exists()){
                        //文件存在，判断是否给基础分
                        Data data1 = dataService.getById(filesList.get(i).getDataId());
                        //存在此任务才处理该文件，有可能任务变更后此文件不需要了，极少数情况，理论上任务下发后不变更
                        if(data1!=null){
                            Files files = filesList.get(i);
                            //先查询是不是已经导入过了，导入过的可能评分了，不能覆盖掉
                            Files exitFiles = filesService.getById(files.getFileId());
                            if(exitFiles==null){
                                //2021年的都给基础分，否则逾期的不给基础分
                                if(data1.getDataYear().equals(2021)){
                                    files.setBaseScore(data1.getBaseScore());
                                }else{
                                    Date upDate = filesList.get(i).getCreateTime();
                                    Calendar calendar = Calendar.getInstance();
                                    calendar.setTime(upDate);
                                    int month = calendar.get(Calendar.MONTH);
                                    if(month<=data1.getDataMonth()){
                                        files.setBaseScore(data1.getBaseScore());
                                    }
                                }
                                saveFiles.add(files);
                            }else{
                                exitFiles.copy(files);
                                saveFiles.add(exitFiles);
                            }
                        }

                    }
                }
                if(saveFiles.size()>0){
                    filesService.saveOrUpdateBatch(saveFiles);
                }
                return data;
            }
        }
        return data;
    }

    /**
     * 跳转评分页面
     * @param fileId
     * @param model
     * @return
     */
    @RequestMapping("/toScore")
    public String toScore(@RequestParam(value = "fileId",required = false) Long fileId,
                          Model model){
        if(ToolUtil.isEmpty(fileId)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        ShiroUser user = ShiroKit.getUser();
        Files files = filesService.getById(fileId);
        Data data = dataService.getById(files.getDataId());
        model.addAttribute("files",files);
        model.addAttribute("data",data);
        if(Constants.LEVEL_CITY.equals(user.getUserLevel())){
            //市级评分
            model.addAttribute("star",files.getStarC());
            model.addAttribute("score",files.getDataScoreC());
            model.addAttribute("remark",files.getRemarkC());
        }
        if(Constants.LEVEL_PROVINCE.equals(user.getUserLevel())){
            //省级评分
            model.addAttribute("star",files.getStarP());
            model.addAttribute("score",files.getDataScoreP());
            model.addAttribute("remark",files.getRemarkP());
        }
        return PREFIX + "toScore.html";
    }

    /**
     * 评分
     * @param fileId
     * @param score
     * @return
     */
    @BussinessLog(value = "评分", key = "fileId,score,remark", dict = FilesDict.class)
    @RequestMapping("/updateScore")
    @ResponseBody
    public ResponseData updateScore(@RequestParam(value = "fileId",required = false) Long fileId,
                                    @RequestParam(value = "score",required = false) BigDecimal score,
                                    @RequestParam(value = "star",required = false) Integer star,
                                    @RequestParam(value = "remark",required = false)String remark){
        ShiroUser user = ShiroKit.getUser();
        if(ToolUtil.isOneEmpty(fileId,score)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Files files = filesService.getById(fileId);
        if(files!=null){
            Data data = dataService.getById(files.getDataId());
            if(data!=null){
                //设置分值不能大于基础分值
                if(score.compareTo(data.getDataScore())==1){
                    throw new ServiceException(BizExceptionEnum.SCORE_OUT);
                }
                //更新分值
                if(user.getUserLevel().equals(Constants.LEVEL_PROVINCE)){
                    files.setDataScoreP(score);
                    files.setStarP(star);
                    files.setRemarkP(remark);
                }
                if(user.getUserLevel().equals(Constants.LEVEL_CITY)){
                    files.setDataScoreC(score);
                    files.setStarC(star);
                    files.setRemarkC(remark);
                }
                files.setScoreTime(new Date());//设置评分时间
                files.setScoreUser(user.getId());
                filesService.updateById(files);
                //添加评分记录
                Score scoreLog = new Score();
                scoreLog.setFileId(fileId);
                scoreLog.setScore(score);
                scoreLog.setUserLevel(user.getUserLevel());
                scoreService.save(scoreLog);
            }
        }
        return SUCCESS_TIP;
    }


    /**
     * 跳转导出部门评分任务
     * @return
     */
    @RequestMapping("/toDeptExport")
    public String toDeptExport(){
        return PREFIX + "dept_export.html";
    }

    /**
     * 根据部门导出上传的任务
     * @return
     */
    @RequestMapping("/exportByDept")
    public void exportByDept(@RequestParam(value = "dept",required = false)Long deptId,
                                     HttpServletRequest request,HttpServletResponse response) throws IOException {
        if(ToolUtil.isEmpty(deptId)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Dept dept = deptService.getById(deptId);
        if(dept==null){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        List<Files> listFiles = filesService.listByDept(deptId);
        if(listFiles==null || listFiles.size()==0){
            throw new ServiceException(BizExceptionEnum.DEPT_NOFILE);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("listFiles",listFiles);
        String json = JSONObject.toJSONString(map);
        String rootPath = FileUtil.getRootPath(request,gunsProperties.getJarName());
        String filePath = Constants.FILES_PATH + "dept" + File.separator ;
        File dir = new File(rootPath+filePath);
        if(!dir.exists()){
            dir.mkdirs();
        }else{
            FileUtil.deleteDir(rootPath+filePath);//删除files/dept下的文件及目录，不包含dept
        }
        File jsonFile = new File(rootPath + filePath + Constants.FILES_JSON);
        if(!jsonFile.exists()){
            jsonFile.createNewFile();
        }
        FileOutputStream outputStream = new FileOutputStream(jsonFile);
        outputStream.write(json.getBytes());
        outputStream.close();

        //json生成后复制上传的文件
        for(int i=0;i<listFiles.size();i++){
            File file = new File(rootPath+listFiles.get(i).getFilePath());
            if(file.exists()){
                FileUtil.copyFile(file,rootPath + filePath);
            }
        }

        String zipPath = rootPath + Constants.FILES_PATH + "dept.zip";
        FileUtil.compressionFile(rootPath + filePath ,zipPath);

        try {
            OutputStream out = response.getOutputStream();
            response.setCharacterEncoding("UTF-8");

            byte[] data = getStream(zipPath);
            // 压缩包名称
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("部门评分任务文件("+dept.getFullName()+").zip", "utf-8"));
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
            IOUtils.write(data, out);
            out.close();
        } catch (IOException e) {
            throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
        }

    }

    /**
     * 跳转导出部门评分
     * @return
     */
    @RequestMapping("/toDeptScoreExport")
    public String toDeptScoreExport(){
        return PREFIX + "dept_score_export.html";
    }

    /**
     * 导出部门评分
     */
    @RequestMapping("/exportScoreByDept")
    public void exportScoreByDept(HttpServletRequest request,HttpServletResponse response) throws IOException {
        ShiroUser user = ShiroKit.getUser();
        if(ToolUtil.isEmpty(user.getDeptId())){
            throw new ServiceException(BizExceptionEnum.USER_NODEPT);
        }
        List<Files> listFiles = filesService.listByDept(user.getDeptId());
        if(listFiles==null || listFiles.size()==0){
            throw new ServiceException(BizExceptionEnum.DEPT_NOFILE);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("listFiles",listFiles);
        String json = JSONObject.toJSONString(map);
        String rootPath = FileUtil.getRootPath(request,gunsProperties.getJarName());
        String filePath = Constants.FILES_PATH + "dept" + File.separator ;
        File dir = new File(rootPath+filePath);
        if(!dir.exists()){
            dir.mkdirs();
        }else{
            FileUtil.deleteDir(rootPath+filePath);//删除files/dept下的文件及目录，不包含dept
        }
        File jsonFile = new File(rootPath + filePath + Constants.FILES_JSON);
        if(!jsonFile.exists()){
            jsonFile.createNewFile();
        }
        FileOutputStream outputStream = new FileOutputStream(jsonFile);
        outputStream.write(json.getBytes());
        outputStream.close();

        String zipPath = rootPath + Constants.FILES_PATH + "deptScore.zip";
        FileUtil.compressionFile(rootPath + filePath ,zipPath);

        try {
            OutputStream out = response.getOutputStream();
            response.setCharacterEncoding("UTF-8");

            byte[] data = getStream(zipPath);
            // 压缩包名称
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("部门评分汇总导出文件("+user.getName()+").zip", "utf-8"));
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
            IOUtils.write(data, out);
            out.close();
        } catch (IOException e) {
            throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
        }
    }


    /**
     * 跳转部门评分导入界面
     * @return
     */
    @RequestMapping("/toImportDeptScore")
    public String toImportDeptScore(){
        return PREFIX + "dept_score_import.html";
    }

    @RequestMapping("/importDeptScore")
    @ResponseBody
    @Transactional
    public Map importDeptScore(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ShiroUser user = ShiroKit.getUser();
        String path = (String) request.getParameter("path");
        if(ToolUtil.isEmpty(path)){
            path = Constants.ZIP_PATH;
        }else{
            path = Constants.UPLOAD_PATH + path + File.separator;
        }
        Map data = new HashMap();
        data.put("code",0);
        data.put("msg","导入部门评分成功");
        // 视频路径
        String filePath = "";
        // 视频名称
        String orgFileName = null;
        // 视频后缀
        String fileExt = null;
        // 文件格式错误信息
        String fileExtError = null;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件
            MultipartFile mf = entity.getValue();
            // 获取文件大小
            long picSize = mf.getSize();
            // 获取原文件名
            String fileName =  mf.getOriginalFilename();
            // 获取图片后缀
            fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (!Constants.ZIP.equals(fileExt)) {
                fileExtError = "请上传zip格式文件";
                data.put("code","1");
                data.put("msg",fileExtError);
                return data;
            } else if (picSize > Constants.ONE_HUNDRED_MB * 10) {
                fileExtError = "文件最大1000M";
                data.put("code","2");
                data.put("msg",fileExtError);
                return data;
            } else {
                // 对原文件名进行重命名
                fileName = UUIDUtil.uuid() + "." + fileExt;
                // 返回文件路径
                String rootPath = FileUtil.getRootPath(request,gunsProperties.getJarName());
                filePath = path + fileName;
                File dic = new File(rootPath + path);
                if(!dic.exists()){
                    dic.mkdirs();
                }
                //上传至服务器
                String realPath = rootPath + filePath;
                mf.transferTo(new File(realPath));

                //上传成功后读取zip
                ZipFile zipFile = new ZipFile(realPath);
                InputStream in = new BufferedInputStream(new FileInputStream(realPath));
                ZipInputStream zin = new ZipInputStream(in);
                ZipEntry ze;
                StringBuffer json = new StringBuffer();
                Map<String,InputStream> streamMap = new HashMap<>();
                while((ze = zin.getNextEntry()) != null){
                    if(ze.toString().endsWith("json")){
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(zipFile.getInputStream(ze)));
                        String line;
                        while((line = br.readLine()) != null){
                            json.append(line);
                        }
                        br.close();
                    }
                }
                zin.close();
                in.close();

                JSONObject jsonObject = JSON.parseObject(json.toString());
                JSONArray filesArr = jsonObject.getJSONArray("listFiles");
                List<Files> filesList = new ArrayList<>();
                for(int i=0;i<filesArr.size();i++){
                    Files files = JSON.toJavaObject(filesArr.getJSONObject(i),Files.class);
                    filesList.add(files);
                }
                //将获取到的评分完成的files更新到主机器
                filesService.updateBatchById(filesList);
                return data;
            }
        }
        return data;
    }




  private byte[] getStream(String filePath) {
        byte[] buffer = null;
        File file = new File(filePath);
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fis!=null)
                    fis.close();
                if(bos!=null)
                    bos.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer;
    }


    /**
     * 跳转评分记录页面
     * @return
     */
    @RequestMapping("/scoreLogIndex")
    public String scoreLogIndex(@RequestParam(value = "fileId", required = false) Long fileId,Model model){
        model.addAttribute("fileId",fileId);
        return PREFIX + "scoreLog.html";
    }

    /**
     * 评分记录列表
     * @return
     */
    @RequestMapping("/scoreLogList")
    @ResponseBody
    public Object list(@RequestParam(value = "fileId", required = false) Long fileId){
        ShiroUser user = ShiroKit.getUser();
        Page<Map<String,Object>> page = scoreService.listScore(fileId,user.getUserLevel());
        return LayuiPageFactory.createPageInfo(page);
    }
}
